package com.shizhanzhe.zxbapp.task.newshare;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;

import com.qq.e.ads.interstitial2.UnifiedInterstitialAD;
import com.qq.e.ads.interstitial2.UnifiedInterstitialADListener;
import com.qq.e.comm.constants.Constants;
import com.qq.e.comm.util.AdError;
import com.shizhanzhe.zxbapp.R;
import com.shizhanzhe.zxbapp.bean.UserBean;
import com.shizhanzhe.zxbapp.url.Path;
import com.shizhanzhe.zxbapp.utils.BitMap;
import com.shizhanzhe.zxbapp.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.zxbapp.utils.Util;
import com.shizhanzhe.zxbapp.utils.a;
import com.shizhanzhe.zxbapp.widget.AdvertisementPopupWindow;
import com.shizhanzhe.zxbapp.widget.ExitDialog;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by zz9527 on 2018/10/19.
 */
public class ShareWebActivity extends Activity implements UnifiedInterstitialADListener {
    private WebView web;
    private TextView price;
    private RecyclerView rv;
    private WebRecyclerAdapter adapter;
    private int count = 5;
    private int shareType = 0;
    private TextView time;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (count > 0) {
                count--;
                time.setText("为防止刷量，"+count+"秒后唤醒微信");
                mHandler.sendEmptyMessageDelayed(shareType, 1000);
            } else {
                time.setVisibility(View.GONE);
                shadow.setVisibility(View.GONE);
                advertisementPopupWindow.dismiss();
                    switch (msg.what) {
                        case 0:
                            getFriend();
                            break;
                        case 1:
                            getFriendQuan();
                            break;
                        default:
                            break;
                    }

            }
        }
    };
    private View share;
    private View shadow;

    private  AdvertisementPopupWindow advertisementPopupWindow;
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shareweb);
        ImmersionBar.with(this).statusBarColor(R.color.them).fitsSystemWindows(true).init();
        findViewById(R.id.backarea).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                if (time.getVisibility()==View.VISIBLE){
                    return;
                }
                finish();
            }
        });
        getIAD().loadAD();
        getYM();
        getData();
        time = findViewById(R.id.time);
        web = findViewById(R.id.web);
        final ProgressBar pg1 = findViewById(R.id.progressBar);
        shadow = findViewById(R.id.shadow);
        share = findViewById(R.id.share);
        web.setBackgroundColor(0);
        web.getSettings().setJavaScriptEnabled(true);
        web.setVerticalScrollBarEnabled(false);
        web.setHorizontalScrollBarEnabled(false);
        //设置webview显示屏幕宽度 不能滑动
//        web.getSettings().setUseWideViewPort(true);
//        web.getSettings().setLoadWithOverviewMode(true);
        // 可以使用插件
        web.getSettings().setPluginState(WebSettings.PluginState.ON);
//        web.getSettings().setBuiltInZoomControls(true);//缩放
//        web.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局

        web.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView webView, int newProgress) {
                if (newProgress == 100) {
                    //加载完网页进度条消失
                    pg1.setVisibility(View.GONE);
                } else {
                    //开始加载网页时显示进度条
                    pg1.setVisibility(View.VISIBLE);
                    //设置进度值
                    pg1.setProgress(newProgress);
                }
            }
        });
        web.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });

        findViewById(R.id.wxq).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (time.getVisibility()==View.VISIBLE){
                    return;
                }
                if (iskou == 1) {
                    count = 5;
                    iad.showAsPopupWindow();
                    shadow.setVisibility(View.VISIBLE);
                    time.setVisibility(View.VISIBLE);
                    share.setFocusable(false);
                    time.setText("为防止刷量，5秒后唤醒微信");
                    shareType = 0;
                    mHandler.sendEmptyMessageDelayed(shareType, 1000);
                } else if (iskou==2){
                    count = 5;
                    advertisementPopupWindow.showDown(web);
                    shadow.setVisibility(View.VISIBLE);
                    time.setVisibility(View.VISIBLE);
                    share.setFocusable(false);
                    time.setText("为防止刷量，5秒后唤醒微信");
                    shareType = 0;
                    mHandler.sendEmptyMessageDelayed(shareType, 1000);
                }else {
                    getFriend();
                }
            }
        });
        findViewById(R.id.wxpyq).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (time.getVisibility()==View.VISIBLE){
                    return;
                }
                if (iskou == 1) {
                    count = 5;
                    iad.showAsPopupWindow();
                    shadow.setVisibility(View.VISIBLE);
                    time.setVisibility(View.VISIBLE);
                    share.setFocusable(false);
                    time.setText("为防止刷量，5秒后唤醒微信");
                    shareType = 1;
                    mHandler.sendEmptyMessageDelayed(shareType, 1000);
                } else if (iskou==2){
                    count = 5;
                    advertisementPopupWindow.showDown(web);
                    shadow.setVisibility(View.VISIBLE);
                    time.setVisibility(View.VISIBLE);
                    share.setFocusable(false);
                    time.setText("为防止刷量，5秒后唤醒微信");
                    shareType = 1;
                    mHandler.sendEmptyMessageDelayed(shareType, 1000);

                } else {
                    getFriendQuan();
                }

            }
        });
        findViewById(R.id.invite).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (time.getVisibility()==View.VISIBLE){
                    return;
                }
                startActivity(new Intent(ShareWebActivity.this, InviteFriendActivity.class));
            }
        });
        price = findViewById(R.id.price);
        rv = findViewById(R.id.rv);
        rv.setFocusable(false);
        rv.setLayoutManager(new LinearLayoutManager(this));
        adapter = new WebRecyclerAdapter(ShareWebActivity.this);
        rv.setAdapter(adapter);
        rv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
//        findViewById(R.id.share).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                SharePopWindow popWindow = new SharePopWindow(ShareWebActivity.this);
        if (Util.isInstallApp(ShareWebActivity.this, "com.tencent.mobileqq")) {
            appid = "weixin://sendreq?appid=wxf0a80d0ac2e82aa7";
            appname = "com.tencent.mobileqq";
        } else if (Util.isInstallApp(ShareWebActivity.this, "com.tencent.mtt")) {
            appid = "weixin://sendreq?appid=wx64f9cf5b17af074d";
            appname = "com.tencent.mtt";
        } else if (Util.isInstallApp(ShareWebActivity.this, "com.ss.android.article.news")) {
            appid = "weixin://sendreq?appid=wx50d801314d9eb858";
            appname = "com.ss.android.article.news";
        } else {
            final ExitDialog mdelDialog = new ExitDialog(ShareWebActivity.this);
            mdelDialog.setExitListener(new ExitDialog.ExitListener() {
                @Override
                public void chooseTrue() {
                    //确定清除
                    mdelDialog.dismiss();
                    Uri content_url = Uri.parse("http://migmkt.qq.com/qbrowser/newindex_22060.html");
                    startActivity(new Intent(Intent.ACTION_VIEW, content_url));
                }

                @Override
                public void chooseFalse() {
                    //取消
                    mdelDialog.dismiss();
                }
            });
            mdelDialog.show();
            mdelDialog.downQQ();
            return;
        }
//                popWindow.showAtLocation(web, Gravity.BOTTOM, 0, 0);
//                popWindow.setListener(new SharePopWindow.ShareListener() {
//                    @Override
//                    public void shareFriend() {
//                        send(ShareWebActivity.this, 0, Path.SHAREURL2(ym, getIntent().getIntExtra("id", 0), UserBean.uid), title, desc);
//                    }
//
//                    @Override
//                    public void shareCircle() {
//                        send(ShareWebActivity.this, 1, Path.SHAREURL2(ym, getIntent().getIntExtra("id", 0), UserBean.uid), title, desc);
//                    }
//
//                    @Override
//                    public void shareQQ() {
//                        Intent intent = new Intent();
//                        intent.setAction("android.intent.action.VIEW");
//                        Uri content_url = Uri.parse(Path.SHAREURL(ym, getIntent().getIntExtra("id", 0), UserBean.uid, 4));
//                        intent.setData(content_url);
//                        intent.setClassName("com.tencent.mtt", "com.tencent.mtt.MainActivity");
//                        startActivity(intent);
//                    }
//
//                    @Override
//                    public void shareQQKJ() {
//                        Intent intent = new Intent();
//                        intent.setAction("android.intent.action.VIEW");
//                        Uri content_url = Uri.parse(Path.SHAREURL(ym, getIntent().getIntExtra("id", 0), UserBean.uid, 5));
//                        intent.setData(content_url);
//                        intent.setClassName("com.tencent.mtt", "com.tencent.mtt.MainActivity");
//                        startActivity(intent);
//                    }
//
//                    @Override
//                    public void shareWB() {
//                        Intent intent = new Intent();
//                        intent.setAction("android.intent.action.VIEW");
//                        Uri content_url = Uri.parse(Path.SHAREURL(ym, getIntent().getIntExtra("id", 0), UserBean.uid, 1));
//                        intent.setData(content_url);
//                        intent.setClassName("com.tencent.mtt", "com.tencent.mtt.MainActivity");
//                        startActivity(intent);
//                    }
//                });
//
//            }
//        });


    }

    private void getFriend() {
        long current = System.currentTimeMillis();//当前时间毫秒数
        String zero = (current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset()) / 1000 + "";//今天零点零分零秒的毫秒数
        String encode = Util.encode(Util.encode(zero + artid + UserBean.uid + "cainimei") + "gun");
        send(ShareWebActivity.this, 0, Path.SHAREURL2(ym, getIntent().getIntExtra("id", 0), UserBean.uid, encode), title, desc);
    }

    private void getFriendQuan() {
        long current = System.currentTimeMillis();//当前时间毫秒数
        String zero = (current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset()) / 1000 + "";//今天零点零分零秒的毫秒数
        String encode = Util.encode(Util.encode(zero + artid + UserBean.uid + "cainimei") + "gun");
        send(ShareWebActivity.this, 1, Path.SHAREURL2(ym, getIntent().getIntExtra("id", 0), UserBean.uid, encode), title, desc);
    }

    String title = "";
    String desc = "";
    Bitmap bm = null;
    private int artid = 0;

    private void getData() {
        final String cssLayout = "<style>*{padding: 0;margin: 0}#webview_content_wrapper{margin: 10px 15px 0 15px;} p { color: #333333; line - height:2e m; font - size:14 px; opacity: 1; } img { margin - top:13 px; margin - bottom:15 px; width: 100 %; }</style > <body><div id='webview_content_wrapper'><p>\n" +
                "        <iframe frameborder=\"0\" src=\"https://v.qq.com/txp/iframe/player.html?vid=p0757hqs7o5\" allowFullScreen=\"true\"></iframe>\n" +
                "    </p></div></body>";


        OkHttpDownloadJsonUtil.downloadJson(this, Path.SHAREDETAIL(getIntent().getIntExtra("id", 0), UserBean.uid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {


            @Override
            public void onsendJson(String json) {

                try {
                    Gson gson = new Gson();
                    final ShareDetail shareDetail = gson.fromJson(json, ShareDetail.class);
                    title = shareDetail.getData().getAname();
                    artid = shareDetail.getData().getArtid();
                    if (UserBean.level > 0) {
                        price.setText(shareDetail.getArtprice().getVipprice());

                    } else {
                        price.setText(shareDetail.getArtprice().getPrice());
                    }
                    desc = title;
                    final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 5, 1, TimeUnit.SECONDS,
                            new LinkedBlockingQueue<Runnable>(100));
                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            bm = BitMap.getHtmlByteArray(ShareWebActivity.this, Path.img(shareDetail.getData().getIcon()));
                        }
                    };
                    threadPoolExecutor.execute(runnable);
                    if (shareDetail.getData().getIsshow() == 0) {
                        String artcontent = shareDetail.getData().getArtcontent();
//                        String htmlModify = artcontent.replaceAll("<br/>", "");
//                        String htmlcontent = cssLayout + "<body><div id='webview_content_wrapper'>" + htmlModify + "</div></body>";
//                        Log.i("_________",htmlcontent);
                        web.loadDataWithBaseURL(null, artcontent, "text/html", "utf-8", null);
                    } else {
                        web.loadUrl(shareDetail.getData().getUrl());
                    }
                    adapter.updateData(1, shareDetail.getRetui());
                    adapter.setOnItemClickListener(new WebRecyclerAdapter.ItemClickListener() {
                        @Override
                        public void onItemClick(int position) {
                            if (time.getVisibility()==View.VISIBLE){
                                return;
                            }
                            startActivity(new Intent(ShareWebActivity.this, ShareWebActivity.class).putExtra("id", shareDetail.getRetui().get(position).getArtid()));
                        }
                    });
                    advertisementPopupWindow = new AdvertisementPopupWindow(ShareWebActivity.this,shareDetail.getData().getTu_img());
                    advertisementPopupWindow.setListener(new AdvertisementPopupWindow.onclick() {
                        @Override
                        public void click() {
                            startActivity(new Intent(ShareWebActivity.this,Webview.class).putExtra("url",shareDetail.getData().getTu_url()).putExtra("type",1));
                        }
                    });
                } catch (Exception e) {
                    Toast.makeText(ShareWebActivity.this, "数据异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    String ym = "";
    int iskou = 1;

    private void getYM() {
        OkHttpDownloadJsonUtil.downloadJson(this, Path.BASE_URL + "/index.php/index/Sharearticle/domain", new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    ym = object.optString("domain");
                    iskou = object.optInt("iskou");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
    private UnifiedInterstitialAD iad;
    private String posId;
    private UnifiedInterstitialAD getIAD() {
        String posId = "2040366161009973";
        if (iad != null && this.posId.equals(posId)) {
            return iad;
        }
        this.posId = posId;
        if (this.iad != null) {
            iad.close();
            iad.destroy();
            iad = null;
        }
        if (iad == null) {
            iad = new UnifiedInterstitialAD(this, "1108917442", posId, this);
        }
        return iad;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (iad != null) {
            iad.destroy();
        }
        ImmersionBar.with(this).destroy();
    }


    IWXAPI iwxapi;
    String appid = "";
    String appname = "";

    public void send(Context paramContext, int paramInt, String url, String title, String desc) {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        iwxapi = WXAPIFactory.createWXAPI(paramContext, "wx8ec35c73c8f4e83e", true);
        // 将应用的appId注册到微信
        iwxapi.registerApp("wx8ec35c73c8f4e83e");
        WXWebpageObject localWXWebpageObject = new WXWebpageObject();
        localWXWebpageObject.webpageUrl = url;
        WXMediaMessage wxMediaMessage = new WXMediaMessage(localWXWebpageObject);
        wxMediaMessage.title = title;
        wxMediaMessage.description = desc;
        if (bm != null) {
            wxMediaMessage.thumbData = Util.bmpToByteArray(Bitmap.createScaledBitmap(bm, 150, 150, true), true);
        } else {
            wxMediaMessage.thumbData = Util.bmpToByteArray(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.logo), 150, 150, true), true);
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = wxMediaMessage;
        req.scene = paramInt;
        iwxapi.sendReq(req);
        Bundle bundle = new Bundle();
        req.toBundle(bundle);
        Intent intent = new Intent();
        intent.putExtras(bundle);
        intent.setClassName("com.tencent.mm", "com.tencent.mm.plugin.base.stub.WXEntryActivity");
        intent.putExtra("_mmessage_sdkVersion", 620824064);
        intent.putExtra("_mmessage_appPackage", appname);
        intent.putExtra("_mmessage_content", appid);
        intent.putExtra("_mmessage_checksum", a.a(appid, 620824064, "com.shizhanzhe.zxbapp"));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        paramContext.startActivity(intent);
        OkHttpDownloadJsonUtil.downloadJson(this, Path.SHARERECORD(artid, UserBean.uid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {

            }
        });
    }

    private static String buildTransaction(String paramString) {
        if (paramString == null) {
        }
        for (paramString = String.valueOf(System.currentTimeMillis()); ; paramString = paramString + System.currentTimeMillis()) {
            return paramString;
        }
    }

    @Override
    public void onADReceive() {

        Log.i("____", "广告加载成功 ！");
    }

    @Override
    public void onNoAD(AdError error) {
        String msg = String.format(Locale.getDefault(), "onNoAD, error code: %d, error msg: %s",
                error.getErrorCode(), error.getErrorMsg());
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onADOpened() {
        Log.i("____", "onADOpened");
    }

    @Override
    public void onADExposure() {
        Log.i("____", "onADExposure");
    }

    @Override
    public void onADClicked() {
        Log.i("____", "onADClicked");
    }

    @Override
    public void onADLeftApplication() {
        Log.i("____", "onADLeftApplication");
    }

    @Override
    public void onADClosed() {
        Log.i("____", "onADClosed");
        getIAD().loadAD();
    }
}
